package com.cfc.stage1;

import org.junit.Test;

/**
 * @description: 最长公共前缀
 *   https://leetcode.cn/problems/longest-common-prefix/description/
 * @author: yangxuan10
 * @create: 2024-04-09 10:42
 **/
public class LongestCommonPrefix {


    @Test
    public void test(){

        String [] strs = new String[]{"flower","flow","flight"};
        System.out.println(longestCommonPrefix(strs));
    }

    public String longestCommonPrefix(String[] strs) {
        int midLength = strs[0].length();
        if (strs.length == 1 || midLength == 0) {
            return strs[0];
        }
        int length = 0;
        char [] chars0 = strs[0].toCharArray();
        for (int i = 1;i < strs.length;i++) {
            char [] chars1 = strs[i].toCharArray();
            if (chars1.length == 0) {
                return "";
            }
            midLength = Math.min(chars1.length, i == 1 ? midLength : length);
            for (int j =0;j < midLength ;j++) {
                if (chars0[j] == chars1[j]) {
                    length=j+1;
                } else {
                    if (j==0) {
                        return "";
                    }
                    break;
                }
            }
            if (length == 0) {
                return "";
            }
        }
        return strs[0].substring(0,length);
    }
}